package cn.com.shadowless.xinning.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mengpeng.mphelper.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import cn.com.shadowless.xinning.MyApplication;
import cn.com.shadowless.xinning.R;
import cn.com.shadowless.xinning.adapter.AdministrativeAdapter;
import cn.com.shadowless.xinning.adapter.CostAdapter;
import cn.com.shadowless.xinning.callback.RequestCallBack;
import cn.com.shadowless.xinning.model.RequestResult;
import cn.com.shadowless.xinning.model.order.AdniminiStrativeOrderInfo;
import cn.com.shadowless.xinning.model.order.ChildResult;
import cn.com.shadowless.xinning.presenter.OrderPresenter;
import cn.com.shadowless.xinning.utils.PreferencesUtils;
import cn.com.shadowless.xinning.view.BaseFragment;
import cn.com.shadowless.xinning.view.activity.OfficeActivity;
import cn.com.shadowless.xinning.view.activity.TabActivity;

/**
 * The type Adnimini strative fragment.
 *
 * @author sHadowLess
 */
public class AdminiStrativeFragment extends BaseFragment {

    /**
     * The Administrative receipt info receipt num.
     */
    @BindView(R.id.administrative_receiptInfo_ReceiptNum)
    TextView administrativeReceiptInfoReceiptNum;
    /**
     * The Administrative receipt info making depart.
     */
    @BindView(R.id.administrative_receiptInfo_MakingDepart)
    TextView administrativeReceiptInfoMakingDepart;
    /**
     * The Administrative receipt info position job.
     */
    @BindView(R.id.administrative_receiptInfo_PositionJob)
    TextView administrativeReceiptInfoPositionJob;
    /**
     * The Administrative receipt info maker.
     */
    @BindView(R.id.administrative_receiptInfo_Maker)
    TextView administrativeReceiptInfoMaker;
    /**
     * The Administrative receipt info make time.
     */
    @BindView(R.id.administrative_receiptInfo_MakeTime)
    TextView administrativeReceiptInfoMakeTime;
    /**
     * The Administrative base info proposer.
     */
    @BindView(R.id.administrative_baseInfo_Proposer)
    TextView administrativeBaseInfoProposer;
    /**
     * The Administrative base info provider.
     */
    @BindView(R.id.administrative_baseInfo_Provider)
    TextView administrativeBaseInfoProvider;
    /**
     * The Administrative base info accrual date.
     */
    @BindView(R.id.administrative_baseInfo_AccrualDate)
    TextView administrativeBaseInfoAccrualDate;
    /**
     * The Administrative base info trading days.
     */
    @BindView(R.id.administrative_baseInfo_TradingDays)
    TextView administrativeBaseInfoTradingDays;
    /**
     * The Administrative base info currency.
     */
    @BindView(R.id.administrative_baseInfo_Currency)
    TextView administrativeBaseInfoCurrency;
    /**
     * The Administrative base info payment method.
     */
    @BindView(R.id.administrative_baseInfo_PaymentMethod)
    TextView administrativeBaseInfoPaymentMethod;
    /**
     * The Administrative base info payment purpose.
     */
    @BindView(R.id.administrative_baseInfo_PaymentPurpose)
    TextView administrativeBaseInfoPaymentPurpose;
    /**
     * The Administrative base info rate.
     */
    @BindView(R.id.administrative_baseInfo_Rate)
    TextView administrativeBaseInfoRate;
    /**
     * The Administrative base info attachments total.
     */
    @BindView(R.id.administrative_baseInfo_AttachmentsTotal)
    TextView administrativeBaseInfoAttachmentsTotal;
    /**
     * The Administrative detail budget directory.
     */
    @BindView(R.id.administrative_detail_BudgetDirectory)
    TextView administrativeDetailBudgetDirectory;
    /**
     * The Administrative detail for years.
     */
    @BindView(R.id.administrative_detail_ForYears)
    TextView administrativeDetailForYears;
    /**
     * The Administrative detail reimbursement way.
     */
    @BindView(R.id.administrative_detail_ReimbursementWay)
    TextView administrativeDetailReimbursementWay;
    /**
     * The Administrative detail reimbursement categories.
     */
    @BindView(R.id.administrative_detail_ReimbursementCategories)
    TextView administrativeDetailReimbursementCategories;

    /**
     * The Administrative base info type.
     */
    @BindView(R.id.administrative_baseInfo_type)
    TextView administrativeBaseInfoType;

    /**
     * The Administrative remark.
     */
    @BindView(R.id.administrative_Remark)
    TextView administrativeRemark;

    /**
     * The Administrative base info total with.
     */
    @BindView(R.id.administrative_baseInfo_totalWith)
    TextView administrativeBaseInfoTotalWith;

    /**
     * The Administrative base info total with out.
     */
    @BindView(R.id.administrative_baseInfo_totalWithOut)
    TextView administrativeBaseInfoTotalWithOut;
    /**
     * The Administrative attach info.
     */
    @BindView(R.id.administrative_attachInfo)
    RecyclerView administrativeAttachInfo;
    /**
     * The Administrative check process.
     */
    @BindView(R.id.administrative_check_Process)
    LinearLayout administrativeCheckProcess;
    /**
     * The Admini strative tab item main tab.
     */
    @BindView(R.id.adminiStrative_tab_item_mainTab)
    LinearLayout adminiStrativeTabItemMainTab;
    /**
     * The Admini strative tab item source tab.
     */
    @BindView(R.id.adminiStrative_tab_item_sourceTab)
    LinearLayout adminiStrativeTabItemSourceTab;
    /**
     * The Admini strative tab item import tab.
     */
    @BindView(R.id.adminiStrative_tab_item_importTab)
    LinearLayout adminiStrativeTabItemImportTab;
    /**
     * The Admini strative tab item amount tab.
     */
    @BindView(R.id.adminiStrative_tab_item_amountTab)
    LinearLayout adminiStrativeTabItemAmountTab;

    private final String url = "api/AdministrationAffExpAccount/LoadCheckHistoryList?%s=";

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_administrative_layout;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        if (null != bundle) {
            String orderId = bundle.getString("orderId");
            String userName = bundle.getString("userName");
            String billCode = bundle.getString("billCode");
            initAdniminiStrativeInfo(orderId, userName, billCode);
            initCheckHistoryList(String.format(url, "id") + orderId, mActivity, administrativeCheckProcess);
        }
    }

    @Override
    protected void initView() {

    }


    private void initAdniminiStrativeInfo(String orderId, String userName, String billCode) {
        OrderPresenter
                .getSingleton()
                .getAdniminiStrativeInfo(orderId, userName, new RequestCallBack<AdniminiStrativeOrderInfo>() {
                    @Override
                    public void success(RequestResult<AdniminiStrativeOrderInfo> result) {
                        String token = result.getLoginToken();
                        String oldToken = PreferencesUtils.getString(MyApplication.getInstance(), "token", "-1");
                        if (result.isSucceed() && null != result.getResult()) {
                            if (null != token && token.equals(oldToken)) {
                                Log.e(TAG, "success: " + result.toString());
                                AdniminiStrativeOrderInfo.DataBean dataBean = result.getResult().getData();
                                List<AdniminiStrativeOrderInfo.DataBean.SourceFormListBean> sourceFormListBeans = dataBean.getSourceFormList();
                                List<AdniminiStrativeOrderInfo.DataBean.ImportItemListBean> importItemListBeans = dataBean.getImportItemList();
                                List<AdniminiStrativeOrderInfo.DataBean.ImportItemListBean.MainPageListBean> mainPageListBeans = dataBean.getMainPageList();
                                List<AdniminiStrativeOrderInfo.DataBean.ImportItemListBean.AmountTotalListBean> amountTotalListBeans = dataBean.getAmountTotalList();
                                List<AdniminiStrativeOrderInfo.DataBean.FileListDTO> fileList = dataBean.getFileList();

                                String id = dataBean.getId();
                                String createTimeString = dataBean.getCreateTimeString();
                                String createUserName = dataBean.getCreateUserName();
                                String departmentName = dataBean.getDepartmentName();
                                String positionName = dataBean.getPositionName();
                                administrativeReceiptInfoReceiptNum.setText(id);
                                administrativeReceiptInfoMakingDepart.setText(departmentName);
                                administrativeReceiptInfoPositionJob.setText(positionName);
                                administrativeReceiptInfoMaker.setText(createUserName);
                                administrativeReceiptInfoMakeTime.setText(createTimeString);


                                String invoiceTypeName = dataBean.getInvoiceTypeName();
                                String proposerName = dataBean.getProposerName();
                                String payDateString = dataBean.getPayDateString();
                                String transactionDateString = dataBean.getTransactionDateString();
                                String currencyName = dataBean.getCurrencyName();
                                String supplierName = dataBean.getSupplierName();
                                String payWayStr = dataBean.getPayWayStr();
                                String payUse = dataBean.getPayUse();
                                String taxRateStr = dataBean.getTaxCode();
                                String accessoryCount = dataBean.getAccessoryCount() + "";
                                String amount = getDecimal(dataBean.getAmount().doubleValue());
                                String amountWithOutDuty = getDecimal(dataBean.getAmountWithOutDuty().doubleValue());
                                administrativeBaseInfoType.setText(invoiceTypeName);
                                administrativeBaseInfoProposer.setText(proposerName);
                                administrativeBaseInfoProvider.setText(supplierName);
                                administrativeBaseInfoAccrualDate.setText(payDateString);
                                administrativeBaseInfoTradingDays.setText(transactionDateString);
                                administrativeBaseInfoCurrency.setText(currencyName);
                                administrativeBaseInfoPaymentMethod.setText(payWayStr);
                                administrativeBaseInfoPaymentPurpose.setText(payUse);
                                administrativeBaseInfoRate.setText(taxRateStr);
                                administrativeBaseInfoAttachmentsTotal.setText(accessoryCount);
                                administrativeBaseInfoTotalWith.setText(amount);
                                administrativeBaseInfoTotalWithOut.setText(amountWithOutDuty);

                                adminiStrativeTabItemMainTab.setOnClickListener(v -> {
                                    EventBus.getDefault().postSticky(
                                            ChildResult
                                                    .builder()
                                                    .billCode(billCode)
                                                    .data(mainPageListBeans)
                                                    .dataName("报销主界面")
                                                    .build()
                                    );
                                    startActivity(new Intent(mActivity, TabActivity.class));
                                });

                                adminiStrativeTabItemSourceTab.setOnClickListener(v -> {
                                    EventBus.getDefault().postSticky(
                                            ChildResult
                                                    .builder()
                                                    .billCode(billCode)
                                                    .data(sourceFormListBeans)
                                                    .dataName("报销来源数据")
                                                    .build()
                                    );
                                    startActivity(new Intent(mActivity, TabActivity.class));
                                });
                                adminiStrativeTabItemImportTab.setOnClickListener(v -> {
                                    EventBus.getDefault().postSticky(
                                            ChildResult
                                                    .builder()
                                                    .billCode(billCode)
                                                    .data(importItemListBeans)
                                                    .dataName("导入EXCEL明细")
                                                    .build()
                                    );
                                    startActivity(new Intent(mActivity, TabActivity.class));
                                });
                                adminiStrativeTabItemAmountTab.setOnClickListener(v -> {
                                    EventBus.getDefault().postSticky(
                                            ChildResult
                                                    .builder()
                                                    .billCode(billCode)
                                                    .data(amountTotalListBeans)
                                                    .dataName("部门金额汇总")
                                                    .build()
                                    );
                                    startActivity(new Intent(mActivity, TabActivity.class));
                                });

                                administrativeAttachInfo.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
                                AdministrativeAdapter administrativeAdapter = new AdministrativeAdapter(R.layout.fragment_adniminstrative_item, fileList);
                                administrativeAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                                    String fileName = fileList.get(position).getFileName();
                                    String fileUrl = fileList.get(position).getFileUrl();
                                    Intent intent = new Intent(mActivity, OfficeActivity.class);
                                    intent.putExtra("fileName", fileName);
                                    intent.putExtra("fileUrl", fileUrl);
                                    mActivity.startActivity(intent);
                                });
                                administrativeAttachInfo.setAdapter(administrativeAdapter);
                                administrativeAdapter.notifyDataSetChanged();

                                String budgetDirectoryName = dataBean.getBudgetDirectoryName();
                                String expenseDateString = dataBean.getExpenseDateString();
                                boolean expenseWay = dataBean.isExpenseWay();
                                String expenseTypeValue = dataBean.getExpenseTypeValue();
                                String expenseType = dataBean.getExpenseType();
                                administrativeDetailBudgetDirectory.setText(budgetDirectoryName);
                                administrativeDetailForYears.setText(expenseDateString);
                                if (expenseWay) {
                                    administrativeDetailReimbursementWay.setText("是");
                                } else {
                                    administrativeDetailReimbursementWay.setText("否");
                                }
                                administrativeDetailReimbursementCategories.setText(expenseTypeValue + expenseType);

                                String remark = dataBean.getRemark();
                                administrativeRemark.setText(remark);
                            } else {
                                ToastUtils.onErrorShowToast("登录态与服务器不一致");
                                initLogoutInfo(mActivity, userName);
                            }
                        } else {
                            ToastUtils.onErrorShowToast("该订单暂无详细信息");
                        }
                    }

                    @Override
                    public void fail(String errorMsg) {
                        Log.e(TAG, "fail: " + errorMsg);
                        ToastUtils.onErrorShowToast(errorMsg);
                    }
                });
    }
}
